<template>
  <div class="box">
      <div class="smt-box">
        <div class="filter-box">
          <div class="smt-tit">
            <p class="title">筛选区</p>
            <el-input
              placeholder="请输入厂家名称"
              v-model="record.companycon"
              suffix-icon="el-icon-search"
              clearable>
            </el-input>
          </div>
          <!-- 所在城市 -->
          <div class="city-box">
          <p class="city-tit">所在城市:</p>
          <ul :class="listType?'city-con show':'city-con hidde'" ref="citycon">
            <li v-for="(item,index) in allList" :key="index" >
              <el-dropdown  :hide-on-click="false" trigger="click">
                    <span class="el-dropdown-link" ref="dropdownName">
                      {{item.name}}
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown" v-if="item.child" ref="dropdown">
                      <el-dropdown-item  v-for="val in item.child" :key="val.id">
                      <el-checkbox-group v-model="val.active">
                        <el-checkbox>
                          {{val.name}}
                        </el-checkbox>
                      </el-checkbox-group>
                      </el-dropdown-item>
                      <div class="btn">
                        <!-- @click="" -->
                      <el-button class="cancel" size="small" @click="goCancel(item,index)">取消</el-button>
                      <el-button type="primary" size="small" class="sure" @click="SureEdit(item,index)">确认</el-button>
                    </div>
                    </el-dropdown-menu> 
                </el-dropdown>
            </li>
          </ul>
          <div class="more" @click="changeType" v-show="listHeight > 40">
              {{ listType ? '收起' : '更多'}}
              <i :class="listType?'el-icon-arrow-up':'el-icon-arrow-down'"></i>
          </div>
          </div>
          <!-- 工厂特色 -->
          <div class="city-box">
          <p class="city-tit" >工厂特色:</p>
          <ul class="city-con" v-if='factoryFeatures.length'>
              <li v-for='(item, index) in factoryFeatures' :key="index">
                <span :class="{'active':item.active}" @click='handleSiftingSort(index, item.active, "factoryFeatures")'> {{item.name}}</span>
              </li>
          </ul>
          </div>
          <!-- 资质 -->
          <div class="city-box">
          <p class="city-tit" >资质:</p>
          <ul class="city-con" v-if='qualification.length'>
              <li v-for='(item, index) in qualification' :key="index">
                <span :class="{'active':item.active}" @click='handleSiftingSort(index, item.active, "qualification")'> {{item.name}}</span>
              </li>
          </ul>
          </div>
          <!-- 工艺分类 -->
          <div class="city-box">
          <p class="city-tit" >工艺分类:</p>
          <ul class="city-con" v-if='craftSort.length'>
              <li v-for='(item, index) in craftSort' :key="index">
                <span :class="{'active':item.active}" @click='handleSiftingSort(index, item.active, "craftSort")'> {{item.name}}</span>
              </li>
          </ul>
          </div>
          <!-- 品质特色 -->
          <div class="city-box">
          <p class="city-tit" > 品质特色:</p>
          <ul class="city-con" v-if='quality.length'>
              <li v-for='(item, index) in quality' :key="index">
                <span :class="{'active':item.active}" @click='handleSiftingSort(index, item.active, "quality")'> {{item.name}}</span>
              </li>
          </ul>
          </div>
          <!-- 筛选条件 -->
          <div class="filterbox" v-if="filter.length > 0">
          <div>
            <el-tag v-for="(item, index) in filter" :key="index" closable  @close="handleClose(item)">
              {{ item.combinationName ? item.combinationName : item.name }}
            </el-tag>
          </div> 
            <p class="reset" @click="goReset()">重置</p>
          </div>
          <div v-else class="empty">暂无筛选项</div>
        </div>
        <!-- 列表 -->
        <div class="content">
          <ul class="list-warpper">
            <li class="list-box" v-for="item in contentList" :key="item.id">
              <div @click="goDetail(item.mfrId)">
                <img class="pic" :src="item.mfrImg" alt=""/>
                <p class="companyname">{{item.mfrName}}</p>
              </div>
                <div class="iconbox" @click="goInquiry(item.mfrId)">
                  <i class="el-icon-service"></i>
                  <p>在线询价</p>
                  <!-- <el-button type="text" @click="goInquiry(item.mfrId)">
                    <i class="el-icon-chat-dot-square iconsize"></i>
                  </el-button> -->
                </div>
            </li>
          </ul>
          <!-- 分页 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="record.currentPage"
              :page-sizes="[8, 20, 32, 48]"
              :page-size="record.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </div>
        <!-- 弹窗 -->
        <el-dialog :visible.sync="dialogFormVisible">
          <p class="dialogtitle">限时优惠！西单最高可享1万元优惠！</p>
          <p class="dialogtit">请填写您的公司名称和真实的手机号码，方便销售与您联系</p>
          <el-form :model="form" :rules="rules" ref="form">
            <el-form-item label="公司名称" :label-width="formLabelWidth" prop="companyName">
              <el-input v-model.trim ="form.companyName"  placeholder="请输入公司名称"></el-input>
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth" prop="userName">
              <el-input v-model.trim ="form.userName" placeholder="请输入姓名"></el-input>
            </el-form-item>
             <el-form-item label="手机号" :label-width="formLabelWidth" prop="tel">
              <el-input v-model.trim ="form.tel" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-form>
            <div class="dialogfooter">
            <el-button type="warning" size="medium" @click="goSumit('form')">提交</el-button>
            </div>
        </el-dialog>
      </div>
  </div>
</template>

<script>
import { getcity,getSMTlist,getSMTlistoption,getPCBinquiry} from "@/api/home.js";
export default {
   name:"pcb",
     data() {
      return {
        record:{
          currentPage:1,
          pageSize: 16,
          companycon: '',//搜索
          filtercities:[],
          filterfactory:[],
          filterqual:[],
          filtercraft:[],
          filtequality:[],
        },
        isShow:true,
        listType:true,//更多 收起
        listHeight:0,//城市高度
        allList:[],
        cities:[
        ],//所有城市
        factoryFeatures: [], // 工厂特色
        qualification: [],//资质
        craftSort: [],// 工艺分类
        quality: [],//品质特色
        filter: [], // 筛选条件
        filterId: [],
        condition:[],//选中分类
        currentIndex:'',//点击次数
        count:0,  
        selectList:[],//选中城市
        selectAllList:[],//选中全部城市
        contentList:[],
        dialogFormVisible:false,//点击弹框
        total:0,
        form: {
          mfrId:'',
          companyName: '   ',
          userName: '',
          tel: '',
        },//在线询价数据
        rules:{
           companyName:[
             {required:true, message: '请输入公司名称', trigger: 'blur'}
           ],
            userName:[
             {required:true, message: '请输入名字', trigger: 'blur'}
           ],
           tel:[
             {required:true, message: '请输入手机号', trigger: 'blur'},
             {pattern: /^1[3-9]\d{9}$/,message: '手机号格式错误'}
           ]
        },
        //表单验证
        formLabelWidth: '120px',
      };
    },
    created(){
      getcity().then(res=>{
        if(res.code == 200){
          this.cities = res.result;
          this.cities.map(item=>{
            item.child.map(item=>{
              this.$set(item,'active', false)
            })
          })
          this.allList = this.cities;
        }else{
           this.$message.error('系统出现错误，请联系管理员');
        }
      });
      getSMTlistoption().then(res=>{
        if(res.code == 200){
          let total = {name:'全部'};
          let total1 = {name:'全部'};
          let total2 = {name:'全部'};
          let total3 = {name:'全部'};
          // 工厂特色
          this.factoryFeatures = res.result[0].level2Options;
          if(!this.factoryFeatures){
            this.factoryFeatures=[];
            this.factoryFeatures.unshift(total)
            this.factoryFeatures.map(item =>{
              item.active = true;
              return item
            })
          }else{
            this.factoryFeatures.unshift(total)
            this.factoryFeatures.map(item =>{
              item.active = false;
              if(item.name == '全部'){
                  item.active = true;
              }
              return item
            })
          }
          // 资质
          this.qualification = res.result[1].level2Options;
          if(!this.qualification){
            this.qualification=[];
            this.qualification.unshift(total1)
            this.qualification.map(item =>{
              item.active = true
              return item
            })
          }else{
            this.qualification.unshift(total1)
            this.qualification.map(item =>{
              item.active = false;
              if(item.name == '全部'){
                  item.active = true;
              }
              return item
            })
          }
          // 工艺分类
          this.craftSort = res.result[2].level2Options;
          if(!this.craftSort){
            this.craftSort=[];
            this.craftSort.unshift(total2)
            this.craftSort.map(item =>{
              item.active = true
              return item
            })
          }else{
            this.craftSort.unshift(total2)
            this.craftSort.map(item =>{
              item.active = false;
              if(item.name == '全部'){
                  item.active = true;
              }
              return item
            })
          }
          // 品质特色
          this.quality = res.result[3].level2Options;
          if(!this.quality){
            this.quality=[];
            this.quality.unshift(total3)
            this.quality.map(item =>{
              item.active = true
              return item
            })
          }else{
            this.quality.unshift(total3)
            this.quality.map(item =>{
              item.active = false;
              if(item.name == '全部'){
                  item.active = true;
              }
              return item
            })
          }
        }else{
          this.$message.error('系统出现错误，请联系管理员');
        }
       
      })
      },
    methods: {
      // 监听公司列表
      handlewatchPCBlist(val){
        let params = {
          'mfrName': val.companycon,
          'page': val.currentPage,
          'size': val.pageSize,
          'factoryFeatureIds': val.filterfactory,
          'qualificationIds':val.filterqual,
          'qualityFeatureIds': val.filtequality,
          'regionIds': val.filtercities,
          'technologyClassificationIds':val.filtercraft
        };
        getSMTlist(params).then(res=>{
          if(res.code == 200){
            this.total = res.result.total;
            this.contentList = res.result.list;
            // console.log(this.contentList,'监听')
          }else{
            this.$message.error('系统出现错误，请联系管理员');
          }
        })
      },
      changeType(){
        this.listType = !this.listType
      },
      //  分类筛选
      handleSiftingSort(index, active, field) {
        let tempArr = this[field];
        if (index !== 0 && !active) {
          tempArr[0].active = false;
        }
        tempArr.forEach((item, arrIndex) => {
          if (index === arrIndex) {
            item.active =  !active;
          }
        });
        if (tempArr[0].active) {
          tempArr.forEach((item, arrIndex) => {
            if (arrIndex > 0) {
              item.active = false;
            }
          });
        }
        if (tempArr.every(item => !item.active) ) {
          tempArr[0].active = true;
        }
        this[field] = tempArr;
        this.handleFilter();
      },
      // 处理筛选条件
        handleFilter() {
        let allList = this.allList;
        let tempArr1 = [];
        let tempArr2 = [];
        let tempArr3 = [];
        let tempArr4 = [];
        let tempArr5 = [];
        this.selectAllList = this.selectAllList.filter(item =>item.active ==true)
        // console.log(this.selectAllList,'数组');
        this.selectAllList.forEach((item) => {
          // 获取父级
          const findItem = allList.find(itemSub => itemSub.child.some(itemThirdSub => itemThirdSub.id === item.id)); 
          // console.log(findItem);
          tempArr1.push({ combinationName: findItem.name + '-' + item.name, ...item});
          let filtercitiesId = [];
          tempArr1.map(val=>{
            filtercitiesId.push(val.id)
            this.record.filtercities =  filtercitiesId;
          })
        });
        this.factoryFeatures.forEach((item) => {
          if (item.active && item.name != '全部') {
            tempArr2.push(item);
            // console.log(tempArr2,'1111');
            let filterfactoryId = []
            tempArr2.map(val=>{
              filterfactoryId.push(val.mfrParamId)
            })
            this.record.filterfactory =  filterfactoryId;
          }
        });
        this.qualification.forEach((item) => {
          if (item.active && item.name != '全部') {
            tempArr3.push(item);
            let filterqualId = [];
            tempArr3.map(val=>{
              filterqualId.push(val.mfrParamId)
            })
            this.record.filterqual =  filterqualId;
          }
        });
        this.craftSort.forEach((item) => {
          if (item.active && item.name != '全部') {
            tempArr4.push(item);
            let filtercraftId = [];
            tempArr4.map(val=>{
              filtercraftId.push(val.mfrParamId)
            })
            this.record.filtercraft =  filtercraftId;
          }
        });
        this.quality.forEach((item) => {
          if (item.active && item.name != '全部') {
            tempArr5.push(item);
            let filterqualityId = [];
            tempArr5.map(val=>{
              filterqualityId.push(val.mfrParamId)
            })
            this.record.filtequality =  filterqualityId;
          }
        });
      
        this.filter = [...tempArr1,...tempArr2,...tempArr3,...tempArr4,...tempArr5];
        // console.log(this.filter,'过滤');
      },
      // 确定按钮
      SureEdit(data,index){
        // 下拉框显示与隐藏
        this.$refs.dropdown[index].$data.showPopper = !this.$refs.dropdown[index].$data.showPopper;
          let arr = data.child.map(function (item) { 
            if(item.active === true){
              return item
            }
          })
          this.selectList = arr.filter(item=>{
            return item
          })
        this.selectList.forEach(item =>{
          if(item.active){
            this.selectAllList.push(item);
          }
        })
        //  判断是否有false
        this.selectAllList.forEach((item,i) => {
          if(item.active === false){
              this.selectAllList.splice(i,1)
          }
          
        })
        this.selectAllList = [...new Set(this.selectAllList)]
        this.handleFilter();
      },
      // 取消按钮
      goCancel(data,index){
        // console.log(data,index)
        let arrList = data.child;
        arrList.map(item =>{
          item.active = false;
        })
        this.$refs.dropdown[index].$data.showPopper = !this.$refs.dropdown[index].$data.showPopper;
      },
      //重置数据true与false；
      handleArrList(){
        this.selectAllList.forEach(item => {
          item.active = !item.active;
        })
        this.record.filtercities =  [];
        this.factoryFeatures.forEach((item,i) => {
          if (item.active) {
            item.active = !item.active
          }
          if(i == 0){
            item.active = true
          }
        });
        this.record.filterfactory =  [];
        this.qualification.forEach((item,i) => {
          if (item.active) {
            item.active = !item.active
          }
          if(i == 0){
            item.active = true
          }
        });
        this.record.filterqual = [];
        this.craftSort.forEach((item,i) => {
          if (item.active) {
            item.active = !item.active
          }
          if(i == 0){
            item.active = true
          }
        });
        this.record.filtercraft =  [];
        this.quality.forEach((item,i) => {
          if (item.active) {
            item.active = !item.active
          }
          if(i == 0){
            item.active = true
          }
        });
         this.record.filtequality = [];
      },
      // 重置
      goReset(){
        this.handleArrList();
        this.filter = [];
      },
      // 筛选条件删除
      handleClose(item){
        let filtercitiesId = [];
        let filterfactoryId = [];
        let filterqualId = [];
        let filtercraftId = [];
        let filterqualityId = [];
        this.selectAllList.forEach((val,i) => {
          if(val.id === item.id){
            val.active = !val.active;
            this.selectAllList.splice(i,1)
            //  this.selectAllList.splice
          }
          if(val.active){
            filtercitiesId.push(val.id)
          }
        })
        this.record.filtercities =  filtercitiesId;
        this.factoryFeatures.forEach((val,i) => {
          if(val.mfrParamId === item.mfrParamId){
            val.active = !val.active;
          }
          if(val.active && val.name != '全部'){
              this.factoryFeatures[0].active = false;
              filterfactoryId.push(val.mfrParamId)
          }   
        });
         this.record.filterfactory =  filterfactoryId;
        //  console.log(this.record.filterfactory,'1111')
        if(this.factoryFeatures.every(item => !item.active)){
          this.factoryFeatures[0].active = true;
        }
        this.qualification.forEach((val,i) => {
          if(val.mfrParamId === item.mfrParamId){
            val.active = !val.active;
          }
          if(val.active && val.name != '全部'){
            this.qualification[0].active = false;
            filterqualId.push(val.mfrParamId)
          }
        });
        this.record.filterqual =  filterqualId;
        if(this.qualification.every(item => !item.active)){
          this.qualification[0].active = true;
        }
        this.craftSort.forEach((val,i) => {
          if(val.mfrParamId === item.mfrParamId){
            val.active = !val.active;
          }
          if(val.active && val.name != '全部'){
            this.craftSort[0].active = false;
            filtercraftId.push(val.mfrParamId)
          }
        });
        this.record.filtercraft =  filtercraftId;
        // console.log(this.record.filtercraft,'1111')
        if(this.craftSort.every(item => !item.active)){
          this.craftSort[0].active = true;
        }
        this.quality.forEach((val,i) => {
          if(val.mfrParamId === item.mfrParamId){
            val.active = !val.active;
          }
          if(val.active && val.name != '全部'){
            this.quality[0].active = false;
            filterqualityId.push(val.mfrParamId)
          }
        });
        this.record.filtequality =  filterqualityId;
        if(this.quality.every(item => !item.active)){
          this.quality[0].active = true;
        }
        this.filter.splice(this.filter.indexOf(item), 1);
      },
      // 跳转详情页
      goDetail(id){
          this.$router.push({
            name:'detail',
            query:{
            	id:id,
            }
        })
          
      },
      // 在线询价
      goInquiry(id){
        this.form.mfrId = id;
        this.dialogFormVisible = true;
      },
      // 询价提交按钮
      goSumit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 调取接口
            getPCBinquiry(this.form).then(res => {
              if(res.code == 200){
                this.$message({
                   message:res.message,
                   type: 'success'
                })
                this.$refs[formName].resetFields();
                this.dialogFormVisible = false;
              }else{
                this.$message.error('提交出现问题');
              }
            })
            
          } else {
            this.$message.error('出现错误，请重新提交');
            return false; 
          }
        });
      },
      // 分页
      handleSizeChange(size) {
        this.record.pageSize = size;
        console.log(this.record.pageSize);
      },
      handleCurrentChange(currentPage) {
        this.record.currentPage = currentPage;
        console.log(this.record.currentPage);
      }
    },
    watch:{
      // 高度变化
      allList:{
        handler(val,oldVal){
           this.$nextTick(function(){
           let cur = this.$refs.citycon;
              if(cur){
                    this.listHeight = cur.clientHeight;
                }
          });
        },
          immediate: true,
          deep: true
      },
      record:{
        handler(val, oldval){
          this.handlewatchPCBlist(val);
        },
        deep:true,
        immediate:true
      }
    },
    mounted(){
      // this.handlePcblist()
    }
}
</script>

<style lang="less" scoped>
@import './../../../assets/style/edit.css';
.smt-box{
  width: 62.5%;
  // padding: 20px 60px;
  // background: #fff;
  margin:20px auto;
}
.filter-box{
  width: 100%;
  background: #fff;
}
.smt-tit{
  width: 100%;
  padding: 13px 0 0 20px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .el-input{
    width: 24%;
  }
  
}
.title{
  font-size: 14px;
  font-weight: 400;
  color: #4370F3;
  line-height: 20px;
}
.city-box{
  width: 100%;
  font-size: 14px;
  // padding: 0 40px;
  display: flex;
  cursor: pointer;
  border-bottom: 1px solid #EEEEEE;;
  
}
.city-tit{
  font-size: 14px;
  line-height: 40px;
  padding-left: 20px;
  font-weight: 600;
  color: #191A24;
  background: #F6F6F6;
  // margin-right: 20px;
  width: 11.6%;
}
.show{
  height: auto;
}
.hidde{
   height: 40px;
   overflow: hidden;
}
.more{
  width: 5%;
  color: #409EFF;
  margin: 0 10px;
}
.city-con{
  display: flex;
  flex-wrap: wrap;
  font-size: 14px; 
  color: #666666;
  li{
    padding: 0 15px;
    line-height: 40px;
    // height: 40px;
  }
}
.empty{
  padding: 20px;
  font-size: 12px;  
  color: #666666;
  line-height: 20px;
}
 .el-dropdown-menu{
    width: 20%;
    display: flex;
    flex-wrap: wrap;

}
.btn{
  width: 100%;
  margin-top: 10px;
  padding-left: 30%;
  // margin: auto;
}
.filterbox{
  width: 100%;
  padding: 20px;
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.filterbox .el-tag{
  margin-right: 10px;
  margin-bottom: 10px;
  color: #4370F3;
}
.reset{
  margin: 0 20px;
  width: 4%;
  cursor: pointer;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}
.active{
  color: #4370F3;
}
.el-divider--horizontal{
    margin: 10px 0 24px;
}
// 列表
.content{
  margin-top: 20px;
  width: 100%;
}
.list-warpper{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.list-box{
  width: 31.5%;
  padding: 0 0 18px;
  background: #fff;
  margin-right: 2%;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(124, 72, 117, 0.1);
}
.list-box:hover{
  box-shadow: 0 0 10px 0 rgba(247, 37, 34,0.2);
  transition: all .3s;
}
.list-box:nth-child(3n){
  margin-right: 0;
}
.pic{
  // width: 100%;
  height: 160px;
  display: block;
  margin: auto;
}
.companyname{
  margin: 17px 0;
  font-size: 18px;
  font-weight: 600;
  color: #191A24;
  text-align: center;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
  padding: 0 20px;
}
.iconbox{
  padding: 8px 15px;
  background: #E50012;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  width: 100px;
  color: #fff;
  margin: auto;
  border-radius: 20px;
  cursor: pointer;
}
.iconsize{
  margin-right: 20px;
  font-size:25px;
  color: #409EFF;
  font-weight: 300;
  margin: auto;
}
.dialogtitle{
  font-size: 25px;
  font-weight: bold;
  color: #E6A23C;
  text-align: center;
  margin-bottom: 10px;
}
.dialogtit{
  font-size: 18px;
  color: #E6A23C;
  text-align: center;
  margin-bottom: 30px;
}
.el-form{
  width: 75%;
  margin: auto;
}
.dialogfooter{
  text-align: center;
}
.el-button--medium {
    padding: 13px 53px;
    font-size: 18px;
    border-radius: 4px;
}
.el-pagination{
  padding: 20px 5px;
  text-align: right;
}
.el-button--text{
  border: 2px solid #409EFF;
  border-radius: 50%;
  width: 40px;
  height: 40px;
}
.content .el-button{
  padding: 0;
}
</style>